package com.longrise.android.byjk.plugins.aboutme.personalInfo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.event.PersonalExchibitionEvent;
import com.longrise.android.byjk.model.ShareParams;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.permission.PermissionUtil;
import com.longrise.android.byjk.plugins.request.AppBaseRequest;
import com.longrise.android.byjk.plugins.request.AppBaseResult;
import com.longrise.android.byjk.plugins.request.ChangeInforRequest;
import com.longrise.android.byjk.plugins.request.RequestThread;
import com.longrise.android.byjk.plugins.vip.integralexchange.IntegralExchangeActivity;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DeviceUtils;
import com.longrise.common.utils.NetUtil;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BaseFrameView;
import com.longrise.android.ui.dialog.ShareDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by sujizhong on 2016/12/15.
 * 展业秀
 */

public class PersonalExhibitionActivity extends BaseActivity implements View.OnClickListener, BaseFrameView.ReloadListener {

    private static final String TAG = "PersonalExhibitionActivity";

    private final String SAVEINSTANCE_IS_INTEGRA = "SAVEINSTANCE_IS_INTEGRA";
    private final int EXCHANGE_WEB_FACE = 100;
    private final int STARTACT_EDIT_REQUEST = 101;

    private final int MSG_PAGE_START = 0;
    private final int MSG_PAGE_ERROR = 1;
    private final int MSG_PAGE_FINISH = 2;
    private final int MSG_CALL_OPTION = 3;
    private final int MSG_SEND_HANDLER = 4;
    private final int MSG_SHARE_OPTION = 5;

    private final int PLATFROM_SEND = 6;
    private final int PLATFROM_CALL = 7;

    private RelativeLayout mRealBack;
    private BaseFrameView mBaseFrameView;
    private WebView mWebView;
    private WebSettings mWebSettings;


    private boolean mLoadIsError;

    private String mUrl;

    private boolean mDestory;
    private boolean mIntegralFrom;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mDestory) {
                return;
            }
            switch (msg.what) {
                case MSG_PAGE_START:
                    mWebView.setVisibility(View.GONE);
                    mBaseFrameView.setVisibility(View.VISIBLE);
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
                    break;

                case MSG_PAGE_ERROR:
                    mWebView.setVisibility(View.GONE);
                    mBaseFrameView.setVisibility(View.VISIBLE);
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
                    break;

                case MSG_PAGE_FINISH:
                    mLoadIsError = false;
                    mBaseFrameView.setVisibility(View.GONE);
                    mWebView.setVisibility(View.VISIBLE);
                    mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    break;

                case MSG_CALL_OPTION:
                    final String phone = (String) msg.obj;
                    getPermission(phone, PLATFROM_CALL);
                    break;

                case MSG_SEND_HANDLER:
                    final String phone1 = (String) msg.obj;
                    getPermission(phone1, PLATFROM_SEND);
                    break;

                case MSG_SHARE_OPTION:
                    try {
                        ShareParams shareParams = (ShareParams) msg.obj;
                        showShare(shareParams.mTitle, shareParams.mContent, shareParams.mUrl, shareParams.mHeadUrl);
                        Tracker_Google.getInstance().addEvent("Exhibition-industry-show", "share", "分享");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_personalexhibition;
    }

    @Override
    public void initView() {
        init();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void init() {
        mRealBack = (RelativeLayout) findViewById(R.id.back_zy);
        mBaseFrameView = (BaseFrameView) findViewById(R.id.personalexbittion_bv);
        mWebView = (WebView) findViewById(R.id.personalexbittion_webview);
        regEvent();

        setWebSetting();
        getExtraData();

        if (checkNetwork()) {
            mHandler.sendEmptyMessage(MSG_PAGE_START);
            request();
        }
    }

    private void getExtraData() {
//        Intent extraIntent = getIntent();
//        if (extraIntent != null && extraIntent.hasExtra(BBWebHelper.FROM_PAGE)) {
//            String value = extraIntent.getStringExtra(BBWebHelper.FROM_PAGE);
//            if (value != null && value.equals(BBWebHelper.PAGE_NAME)) {
//                mIntegralFrom = true;
//            } else {
//                mIntegralFrom = false;
//            }
//        }
    }

    private void setWebSetting() {
        mWebSettings = mWebView.getSettings();

        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.addJavascriptInterface(new PersonalJSCallback(), "bb");
    }

    @Override
    public void onReload(View v) {
        if (checkNetwork()) {
            if (TextUtils.isEmpty(mUrl)) {
                mHandler.sendEmptyMessage(MSG_PAGE_START);
                request();
            } else {
                load(getUrl());
            }
        }
    }

    private void getPermission(final String phone, final int platFrom) {
        PermissionUtil.Permission permission = null;
        String title = null;
        String msg = null;
        if (platFrom == PLATFROM_CALL) {
            permission = PermissionUtil.Permission.PHONE;
            title = getString(R.string.call_permission);
            msg = getString(R.string.call_permission_hint);
        } else if (platFrom == PLATFROM_SEND) {
            permission = PermissionUtil.Permission.SMS;
            title = getString(R.string.send_permission);
            msg = getString(R.string.send_permission_hint);
        }

        PermissionUtil.getInstance().requestPermission(PersonalExhibitionActivity.this, permission, title, msg, new PermissionUtil.PermissionCallBack() {
            @Override
            public void onSuccess() {
                if (platFrom == PLATFROM_CALL) {
                    openActivity(Intent.ACTION_DIAL, phone);
                } else if (platFrom == PLATFROM_SEND) {
                    openActivity(Intent.ACTION_SEND, phone);
                }
            }

            @Override
            public void onDenied() {

            }
        });
    }

    private class PersonalJSCallback {

        public PersonalJSCallback() {
        }

        @JavascriptInterface
        public void loadFinish() {
            Message message = mHandler.obtainMessage();
            if (mLoadIsError) {
                message.what = MSG_PAGE_ERROR;
            } else {
                message.what = MSG_PAGE_FINISH;
            }
            mHandler.sendMessage(message);
        }

        @JavascriptInterface
        public void shareParams(String title, String sharepath, String sharecontent) {
        }

        @JavascriptInterface
        public void showHintMsg(String msg) {
        }

        @JavascriptInterface
        public void pageBack(boolean isback) {
        }

        @JavascriptInterface
        public void getTitle(String title) {
        }

        @JavascriptInterface
        public void scrollChange(boolean isTop) {
        }

        @JavascriptInterface
        public void showCommentBox() {
        }

        @JavascriptInterface
        public void call(String phone) {
            if (!TextUtils.isEmpty(phone)) {
                mHandler.sendMessage(getMessage(MSG_CALL_OPTION, phone));
            }
        }

        @JavascriptInterface
        public void sendMsg(String phone) {
            if (!TextUtils.isEmpty(phone)) { //短信暂时取消
//                mHandler.sendMessage(getMessage(MSG_SEND_HANDLER, phone));
            }
        }

        @JavascriptInterface
        public void share(String url, String title, String content, String headurl) {
            if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                final ShareParams shareParams = new ShareParams();
                shareParams.mUrl = url;
                shareParams.mTitle = title;
                shareParams.mContent = content;
                shareParams.mHeadUrl = headurl;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!isFinishing()) {
                            ShareDialog shareDialog = new ShareDialog(PersonalExhibitionActivity.this);
                            shareDialog.setShareParame(shareParams);
                            shareDialog.setCallback(mCallback);
                            shareDialog.show();
                        }
                    }
                });
            }
        }

        @JavascriptInterface
        public void menuBarStatus(final boolean isShowing) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    backStatus(isShowing);
                }
            });
        }

        @JavascriptInterface
        public void editData() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(PersonalExhibitionActivity.this, PersonalInfoActivity.class);
                    startActivityForResult(intent, STARTACT_EDIT_REQUEST);
                }
            });
        }

        @JavascriptInterface
        public void changeFace() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Intent exchangeIntent = new Intent(PersonalExhibitionActivity.this, IntegralExchangeActivity.class);
                    startActivity(exchangeIntent);
                }
            });
        }

        @JavascriptInterface
        public void getDeviceInfor() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:setDeviceInfoForGA('" + DeviceUtils.getVersionName() + "')");
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeSkin(PersonalExchibitionEvent event) {
        switch (event.getCategory()) {
            case GHPF: //更换皮肤 重新加载一下地址
                request();
                Tracker_Google.getInstance().addGoogleScreenName("展业秀更换背景");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == STARTACT_EDIT_REQUEST) {
            if (checkNetwork()) {
                request();
            }
        }
    }

    private void backStatus(boolean isEnable) {
        mRealBack.setVisibility(isEnable ? View.VISIBLE : View.GONE);
    }

    private Message getMessage(int msgType, Object obj) {
        Message msg = new Message();
        msg.what = msgType;
        if (obj != null) {
            msg.obj = obj;
        }
        return msg;
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
                mLoadIsError = true;
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (checkNetwork()) {
                mHandler.sendEmptyMessage(MSG_PAGE_START);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mLoadIsError) {
                mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            } else {
                mHandler.sendEmptyMessage(MSG_PAGE_FINISH);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLoadIsError = true;
        }
    };

    private void request() {
//        EntityBean bean = new EntityBean();
//        bean.set("urltype", "grzy");
//        EntityBean reqBean = new EntityBean();
//        reqBean.set("bean", bean);
//        PersionRequest persionRequest = new PersionRequest(new PersonalResult());
//        persionRequest.request(this, "bbt_getAppEntryPath", reqBean);

        ChangeInforRequest changeInforRequest = new ChangeInforRequest(new PersonalResult1());
        changeInforRequest.setApi("bbt_getAppEntryPath");
        RequestThread requestThread = new RequestThread(changeInforRequest);
        requestThread.request(this, AppBaseRequest.APP_REQUEST_TAG, null);
    }

    private class PersonalResult1 implements AppBaseResult {

        @Override
        public void onSuccess(Object result) {
            EntityBean bean = (EntityBean) result;
            if (bean != null && bean.getInt("resultstate") == 1) {
                parse(bean.getBean("result"));
            } else {
                mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            }
        }

        @Override
        public void onFailed(String errorLog) {
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
        }

        @Override
        public void onFinish() {

        }
    }

    private void parse(EntityBean bean) {
        mUrl = bean.getString("personalpage");
        load(getUrl());
    }

    private String getUrl() {
        int widthDP = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(mUrl);
        builder.append("?cardno=");
        builder.append(UserInfor.getInstance().getUsersfzh());
        builder.append("&");
        builder.append("userid=");
        builder.append(UserInfor.getInstance().getUserid());
        builder.append("&");
        builder.append("screenwidth=");
        try {
            int screenWidth = AppUtil.getScreenWidth();
            widthDP = AppUtil.px2dip(screenWidth);
        } catch (Exception e) {
            e.printStackTrace();
        }
        builder.append(widthDP);
        mUrl = builder.toString();
        return mUrl;
    }

    private void load(String url) {
        mWebView.loadUrl(url);
    }

    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return false;
        } else {
            return true;
        }
    }

    private void openActivity(String action, String phone) {
        if (!TextUtils.isEmpty(phone)) {
            Intent intent = new Intent(action, action.equals(Intent.ACTION_DIAL) ? Uri.parse("tel:" + phone) : Uri.parse("smsto:" + phone));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    private void regEvent() {
        mRealBack.setOnClickListener(this);
        mBaseFrameView.setOnReloadListener(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("personalurl", mUrl);
        outState.putBoolean(SAVEINSTANCE_IS_INTEGRA, mIntegralFrom);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mUrl = savedInstanceState.getString("personalurl");
            mIntegralFrom = savedInstanceState.getBoolean(SAVEINSTANCE_IS_INTEGRA);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_zy:
                finish();
                break;
        }
    }

    private void release() {
        if (mWebSettings != null) {
            mWebSettings.setJavaScriptEnabled(false);
        }
        if (mWebView != null) {
            mWebView.clearHistory();
            mWebView.destroy();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void showShare(String shareTitle, String shareContent, String shareUrl, String headUrl) throws Exception {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
//        oks.setDialogMode();
        oks.disableSSOWhenAuthorize();
        oks.setTitle(shareTitle);
        oks.setTitleUrl(shareUrl);
        String content = "";
        if (shareContent.length() > 50) {
            content = shareContent.substring(0, 50).replace("&amp;", "&");
            oks.setText(content);
        } else {
            oks.setText(shareContent.replace("&amp;", "&"));
        }
//        oks.setImagePath(FolderConstants.ICON_DIR + "/logoshare.jpg");
        oks.setImageUrl(headUrl);
        oks.setUrl(shareUrl);
        oks.setSiteUrl(shareUrl);
        oks.show(this);
    }

    private ShareDialog.ShareCallback mCallback = new ShareDialog.ShareCallback() {
        @Override
        public void shareSuccess() {
//              ShareGetIntegralHelper.toShowIntegral(PersonalExhibitionActivity.this,"share");
        }

        @Override
        public void shareFailed() {

        }
    };


    @Override
    protected void onDestroy() {
        release();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mDestory = true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
